package com.example.shortmessage.tips.dialog;


import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.example.shortmessage.base.BaseStyle;
import com.example.shortmessage.data.constant.DialogConst;
import com.example.shortmessage.data.constant.FontsConst;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 加载中对话框
 * @author 27638
 */
public class WaitingDialog {
    private static WaitingDialog instance;
    private static AlertDialog alertDialog;
    private Timer timer;
    private static int i= 0;
    private static Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            i++;
            textView.setText(DialogConst.WAIT[i%4]);
            super.handleMessage(msg);
        }
    };
    private static TextView textView;

    private WaitingDialog(){

    }

    public static WaitingDialog getInstance() {
        if (instance == null) {
            synchronized (WaitingDialog.class){
                if (instance == null) {
                    instance = new WaitingDialog();
                }
            }
        }
        return instance;
    }
    public void show(@NonNull Context context){
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(context);
        i=0;
        textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        new BaseStyle().set(context, textView, FontsConst.TV_CONTENT);
        textView.setPadding(20, 50, 20, 50);
        textView.setText(DialogConst.WAIT[i]);
        normalDialog.setView(textView);
        normalDialog.setCancelable(false);
        alertDialog = normalDialog.create();
        alertDialog.show();
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        },0,500);
    }
    public void dismiss(){
        timer.cancel();
        timer=null;
        alertDialog.dismiss();
    }

}
